﻿using System;
using DevExpress.Web.Data;
using ITViet.Web.App_Code;
using ITViet.Services;
using ITViet.Domains;
using System.Data.SqlClient;
using DevExpress.Web.ASPxTreeList;

namespace ITViet.Web.Admin
{
	public partial class ProCategoryList : AdminBasePage
	{
		#region Properties
		private string m_innerError = string.Empty;
		private string ERR0001 = "fk_tblproduct_tblproductcategory";
		private string ERR0002 = "error|";

		internal override int RequiredPermission
		{
			get
			{
				return (int)FunctionList.Product;
			}
		}

		private int CategoryId
		{
			get
			{
				int Id = 0;
				int.TryParse(hfCategoryId.Value, out Id);
				return Id;
			}
		}

		private int LocaleId
		{
			get
			{
				int Id = 0;
				int.TryParse(hfLocaleId.Value, out Id);
				return Id;
			}
		}

		#endregion

		#region Events

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsCallback && !IsPostBack)
			{
				LoadPage();
				LoadList();
			}
			if (tlCategory.IsCallback)
			{
				LoadList();
			}
		}

		private string LoadLocale()
		{
			TList<ProCategoryLocale> listc = new ProCategoryLocaleService().GetByCategoryId(CategoryId);
			foreach (ProCategoryLocale item in listc)
			{
				if (item.LanguageId == (int)cbxLanguage.Value)
				{
					return string.Format("{0}|{1}|{2}|{3}", "[locale]", item.Id, item.Name, item.Description);
				}
			}
			return string.Format("{0}|{1}|{2}|{3}", "[locale]", 0, string.Empty, string.Empty);
		}

		protected void tlCategory_CustomJSProperties(object sender, DevExpress.Web.ASPxTreeList.TreeListCustomJSPropertiesEventArgs e)
		{
			e.Properties["cpInnerError"] = m_innerError;
		}

		protected void tlCategory_CustomCallback(object sender, DevExpress.Web.ASPxTreeList.TreeListCustomCallbackEventArgs e)
		{
			if (e.Argument.StartsWith("locale"))
			{
				if (LocaleId == 0)
					SaveLocale();
				else
					UpdateLocale();
			}
		}

		protected void tlCategory_NodeDeleting(object sender, ASPxDataDeletingEventArgs e)
		{
			int Id = 0;
			int.TryParse(e.Keys["Id"].ToString(), out Id);
			Delete(Id);
			SetStateGrid(sender, e);
		}

		protected void tlCategory_NodeInserting(object sender, ASPxDataInsertingEventArgs e)
		{
			string name = string.Empty;
			if (e.NewValues["Name"] != null)
			{
				name = e.NewValues["Name"].ToString();
			}

			Insert(name, e.NewValues["ParentId"] as int?);
			SetStateGrid(sender, e);
		}

		protected void tlCategory_NodeUpdating(object sender, ASPxDataUpdatingEventArgs e)
		{
			int Id = 0;
			int.TryParse(e.Keys["Id"].ToString(), out Id);
			string name = string.Empty;
			if (e.NewValues["Name"] != null)
			{
				name = e.NewValues["Name"].ToString();
			}
			Update(Id, name);
			SetStateGrid(sender, e);
		}

		protected void tlCategory_CellEditorInitialize(object sender, DevExpress.Web.ASPxTreeList.TreeListColumnEditorEventArgs e)
		{
			if (e.Column.FieldName == "CreatedDate")
			{
				if (tlCategory.IsNewNodeEditing || tlCategory.IsEditing)
				{
					e.Editor.Value = DateTime.Now;
					e.Editor.Enabled = false;
				}
				return;
			}

			if (e.Column.FieldName == "CreatedBy")
			{
				if (tlCategory.IsNewNodeEditing || tlCategory.IsEditing)
				{
					// need recode
					e.Editor.Value = CurrentUser.Username;
					e.Editor.Enabled = false;
				}
			}
		}

		//protected void gvList_CommandButtonInitialize(object sender, ASPxGridViewCommandButtonEventArgs e)
		//{
		//  if (!CanDelete && e.Button.ButtonType == ColumnCommandButtonType.Delete)
		//    e.Visible = false;
		//  if (!CanModify && e.Button.ButtonType == ColumnCommandButtonType.Edit)
		//  {
		//    e.Visible = false;
		//  }
		//  if (!CanModify && e.Button.ButtonType == ColumnCommandButtonType.New)
		//  {
		//    e.Visible = false;
		//  }
		//}

		protected void gvList_DataBound(object sender, EventArgs e)
		{
			if (!CanModify)
			{
				(tlCategory.Columns["Command"] as TreeListCommandColumn).NewButton.Visible = false;
				(tlCategory.Columns["Locale"] as TreeListCommandColumn).Visible = false;
			}
		}

		protected void CtrlCallback_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
		{
			if (e.Parameter.StartsWith("loadlocale"))
			{
				e.Result = LoadLocale();
			}
			else if (e.Parameter.StartsWith("save"))
			{
				if (LocaleId == 0)
					e.Result = SaveLocale();
				else
					e.Result = UpdateLocale();
			}
		}

		#endregion

		#region Methods

		private void LoadPage()
		{
			xdsLanguage.DataFile = XmlStatusFile;
			cbxLanguage.Value = CurrentLanguage.Id;
		}

		private void LoadList()
		{
			tlCategory.DataSource = new ProductCategoryService().GetAll();
			tlCategory.DataBind();
		}

		private void SetStateGrid(object sender, System.ComponentModel.CancelEventArgs e)
		{
			ASPxTreeList gv = sender as ASPxTreeList;
			e.Cancel = true;
			gv.CancelEdit();
			LoadList();
		}

		private void Insert(string name, int? parentId)
		{
			if (string.IsNullOrEmpty(name))
			{
				m_innerError = ERR0002 + string.Format(Resources.Messages.ERR0007, Resources.Strings.Name);
				return;
			}

			if (parentId.HasValue)
			{
				TreeListNode parentNode = tlCategory.FindNodeByKeyValue(parentId.ToString());
				if (parentNode != null && parentNode.Level > 1)
				{
					m_innerError = ERR0002 + string.Format(Resources.Messages.ERR0068, Resources.Strings.Category, "2");
					return;
				}
			}

			ProductCategory pc = new ProductCategory();
			pc.Name = name;
			pc.Code = VietnameseString.Convert(name);
			pc.ParentId = parentId;
			pc.CreatedDate = DateTime.Now;
			pc.CreatedBy = CurrentUser.Username;
			try
			{
				ProductCategoryService pcservice = new ProductCategoryService();
				pcservice.Save(pc);
			}
			catch (Exception ex)
			{
				WriteLog("ProCategoryList::Insert ProductCategory", ex);
				m_innerError = ERR0002 + Resources.Messages.ERR0004;
			}
		}

		private void Update(int Id, string name)
		{
			if (Id == 0)
			{
				m_innerError = ERR0002 + Resources.Messages.ERR0004;
				return;
			}
			if (string.IsNullOrEmpty(name))
			{
				m_innerError = ERR0002 + string.Format(Resources.Messages.ERR0007, Resources.Strings.Name);
				return;
			}
			try
			{
				ProductCategoryService pcservice = new ProductCategoryService();
				ProductCategory pc = pcservice.GetById(Id);
				pc.Name = name;
				pc.Code = VietnameseString.Convert(name);
				pcservice.Update(pc);
			}
			catch (Exception ex)
			{
				WriteLog("ProductCategory.aspx::Update ProductCategory", ex);
				m_innerError = ERR0002 + Resources.Messages.ERR0004;
			}
		}

		private void Delete(int Id)
		{
			if (Id == 0)
			{
				m_innerError = ERR0002 + Resources.Messages.ERR0060;
				return;
			}
			try
			{
				if (new ProductService().GetByCategoryId(Id).Count > 0)
				{
					m_innerError = ERR0002 + string.Format(Resources.Messages.ERR0063, Resources.Strings.Category, Resources.Strings.Product);
					return;
				}
				ProductCategoryService pcservice = new ProductCategoryService();
				pcservice.DeleteAllById(Id);
			}
			catch (SqlException ex)
			{
				if (ex.Message.ToLower().IndexOf(ERR0001.ToLower()) != -1)
				{
					WriteLog("ProductCategory.aspx::Delete ProductCategory", ex);
					m_innerError = ERR0002 + string.Format(Resources.Messages.ERR0063, Resources.Strings.Category, Resources.Strings.Product);
				}
				else
					throw new Exception(ex.Message, ex);
			}
			catch (Exception ex)
			{
				WriteLog("ProductCategory.aspx::Delete ProductCategory", ex);
				m_innerError = ERR0002 + Resources.Messages.ERR0060;
			}
		}

		private string SaveLocale()
		{

			if (CategoryId == 0)
			{
				return m_innerError = ERR0002 + Resources.Messages.ERR0060;
			}
			if (string.IsNullOrEmpty(txtNameLocale.Text.Trim()))
			{
				return m_innerError = ERR0002 + string.Format(Resources.Messages.ERR0007, Resources.Strings.Name);
			}
			try
			{
				ProCategoryLocale cl = new ProCategoryLocale();
				cl.Name = txtNameLocale.Text.Trim();
				cl.Description = mmDescription.Text.Trim();
				cl.CategoryId = CategoryId;
				cl.LanguageId = (int)cbxLanguage.Value;
				new ProCategoryLocaleService().Save(cl);
				return "[save]";
			}
			catch (Exception ex)
			{
				WriteLog("ProductCategory.aspx::Save ProCategoryLocale", ex);
				return ERR0002 + Resources.Messages.ERR0060;
			}

		}

		private string UpdateLocale()
		{
			if (LocaleId == 0)
			{
				return ERR0002 + Resources.Messages.ERR0060;
			}
			if (string.IsNullOrEmpty(txtNameLocale.Text.Trim()))
			{
				return ERR0002 + string.Format(Resources.Messages.ERR0007, Resources.Strings.Name);
			}
			try
			{
				ProCategoryLocaleService cs = new ProCategoryLocaleService();
				ProCategoryLocale c = cs.GetById(LocaleId);
				c.Name = txtNameLocale.Text.Trim();
				c.Description = mmDescription.Text.Trim();
				cs.Update(c);
				return "[save]";
			}
			catch (Exception ex)
			{
				WriteLog("ProductCategory.aspx::Update ProCategoryLocale", ex);
				return ERR0002 + Resources.Messages.ERR0060;
			}
		}

		#endregion
	}
}
